import store from '../store'
const baseURL = 'https://api.benlv.top/api/rest/'
const instance = {
  get(url) {
    const header = { Authorization: store.state.hasLogin ? store.state.userInfo.token : '' }
    url = url.startsWith('http') ? url : baseURL + url
    return uni.request({ url, header, timeout: 10000 })
  },
  post(url, data) {
    const header = { Authorization: store.state.hasLogin ? store.state.userInfo.token : '' }
    url = url.startsWith('http') ? url : baseURL + url
    return uni.request({ url, method: 'POST', timeout: 10000, header, data })
  }
}

export const httpGet = async({ url }) => {
  const [err, data] = await instance.get(url)
  if (data) {
    if (data.statusCode === 200) {
      return [, data.data]
    }
  }
  return [err]
}

export const httpPOST = async({ url, param }) => {
  const [err, data] = await instance.post(url, param)
  if (data) {
    if (data.statusCode === 200) {
      return [, data.data]
    } else if (data.data && data.data.code === 'invalid-jwt') {
      store.commit('loginOut')
    }
  }
  return [err]
}

export default { httpGet, httpPOST }
